package com.eightbears.beboy.ui.merchant.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ShopPowerAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PutFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.EditDataDialog;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.ManagerEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_MANAGERLIST;
import static com.eightbears.beboy.base.util.CommonAPI.URL_UPDATEMANAGER;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.entity.UserEntity.LOCATION_MANAGER;
import static com.eightbears.beboy.entity.UserEntity.LOCATION_SHOP_MANAGER;

public class ShopPowerManageActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    public static final String STATUS_OPEN = "1";
    public static final String STATUS_CLOSE = "3";


    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.btn_add_manager)
    LinearLayout btn_add_manager;

    private String locationName;
    private String nickName, accountStatus;

    private ShopPowerAdapter shopPowerAdapter;
    private UserEntity.Shop shop;
    private ManagerEntity.Manager manager;
    private EditDataDialog editDataDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_power_manage);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText(R.string.text_power_manager);
        UserEntity userEntity = SPUtil.getUser();
        shop = userEntity.getData().getShops().get(0);

        if (shop.getLevel().equals(LOCATION_SHOP_MANAGER)) {
            locationName = getString(R.string.text_shop_manager_name);
            btn_add_manager.setVisibility(View.VISIBLE);
        } else if (shop.getLevel().equals(LOCATION_MANAGER)) {
            locationName = getString(R.string.text_manager_name);
            btn_add_manager.setVisibility(View.GONE);
        }
        tv_location.setText(locationName);
        initAdapter();
        initEditDialog();
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });

        shopPowerAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                manager = (ManagerEntity.Manager) adapter.getData().get(position);

                switch (view.getId()) {
                    case R.id.ll_edit_name:
                        editDataDialog.show();
                        break;
                    case R.id.tb_sel:
                        accountStatus = manager.changeStatus();
                        updateData();
                        break;
                }
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.btn_add_manager) void addManager(){
        startLocalActivity(this, PickManagerContactsActivity.class);
    }

    private void initEditDialog() {
        editDataDialog = new EditDataDialog(this);
        editDataDialog.setTitleText(getString(R.string.text_edit_other_name_title));
        editDataDialog.setEditHintText(getString(R.string.text_input_other_name));
        editDataDialog.setOnItemClickListener(new EditDataDialog.DialogEditNameListener() {
            @Override
            public void onSetDialogNumOneListener(View v, String name) {
                switch (v.getId()) {
                    case R.id.btn_cancel:
                        editDataDialog.dismiss();
                        break;
                    case R.id.btn_editdialog_ensure:
                        nickName = name;
                        if (TextUtils.isEmpty(nickName)) {
                            ShowToast.showShortToast(getString(R.string.alert_input_empty));
                            return;
                        }
                        manager.setName(name);
                        shopPowerAdapter.notifyDataSetChanged();
                        updateData();
                        editDataDialog.dismiss();
                        break;
                }
            }
        });

    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        shopPowerAdapter = new ShopPowerAdapter();
        shopPowerAdapter.openLoadAnimation();
        rv_list.setAdapter(shopPowerAdapter);
    }

    private void getData() {
        OkHttpUtils.get().url(URL_MANAGERLIST)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("shop_id", shop.getShop_id())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                ManagerEntity managerEntity = GsonUtil.fromJson(response, ManagerEntity.class);

                if (managerEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    shopPowerAdapter.setNewData(managerEntity.getData());
                    shopPowerAdapter.loadMoreComplete();
                }
            }

            @Override
            public void onError(Call request, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    private void updateData() {
        PutFormBuilder builder = OkHttpUtils.put();//创建请求构建器
        builder.url(URL_UPDATEMANAGER + String.valueOf(manager.getId()));
        builder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        if(!TextUtils.isEmpty(nickName)) {
            builder.addParams("name", nickName);
        }
        if(!TextUtils.isEmpty(accountStatus)) {
            builder.addParams("status", accountStatus);
        }
        builder.build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                ShowToast.showShortToast(getString(R.string.alert_edit_success));
                nickName = accountStatus = null;
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError((Activity) mContext, status_error);
            }
        });
    }

    @Override
    public void onRefresh() {
        shopPowerAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                shopPowerAdapter.getData().clear();
                getData();
            }
        }, delayMillis);
    }
}
